package com.example.springboot.config.bootcustomize.parameteranotation;

import com.example.springboot.config.anotation.parameterAnotation.UserParam;
import com.example.springboot.entity.User;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 实现参数解析器
 *
 * @Author:ChenZhangKun
 * @Date: 2021/5/9 16:06
 */
public class UserParamAnnotationImpl implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        // 参数列表是否有这个注解和拥有user这个实体
        return methodParameter.getParameterType().isAssignableFrom(User.class) && methodParameter.hasParameterAnnotation(UserParam.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        // 这里直接进行绑定，可以根据需求，通过拦截器request来进行设置
        User user = new User();
        user.setId(5);
        user.setLastName("czk");
        user.setEmail("jkjk");
        return user;
    }
}
